﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.IO;

namespace SetEnv
{
    class SetBoxEnv
    {
        public bool SetEnv(string env)
        {
            try
            {
                GetInputValue getValue = new GetInputValue();
                getValue.InitializeEvnData(env);

                string proxyOverride = getValue.ProxyOverride;
                string proxyServer = getValue.ProxyServer;
                int proxyEnable = getValue.ProxyEnable == "1" ? 1 : 0;
                //int proxyEnable=int.Parse(getValue.ProxyEnable);
                string hostPath = getValue.HostPath;

                SetHost(env, hostPath);
                SetRegedit(proxyOverride, proxyServer, proxyEnable);
                SetDefaultConnecSet(proxyEnable);

                Reflush();
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        /// <summary>
        /// Set host from under "host" folder or "\\hioffs01\ProjectShare\OfficeLive\Temp\Hosts"
        /// </summary>
        /// <param name="env">The enverienment</param>
        /// <returns>Get the host secussess</returns>
        private void SetHost(string env, string hostPath)
        {
            //hostPath = AppDomain.CurrentDomain.BaseDirectory + hostPath;
            string PathEtc = @"C:\Windows\System32\drivers\etc\hosts";
            try
            {
                if (File.Exists(hostPath))
                {
                    File.Copy(hostPath, PathEtc, true);
                }
                if (!string.IsNullOrEmpty(hostPath) & !File.Exists(hostPath))
                {
                    hostPath = @"Source\host\" + hostPath;
                    hostPath = AppDomain.CurrentDomain.BaseDirectory + hostPath;
                    File.Copy(hostPath, PathEtc, true);
                }
                if (string.IsNullOrEmpty(hostPath))
                {
                    string hostName = string.Format("hosts." + env + ".txt");
                    try
                    {
                        hostPath = @"Source\host\" + hostName;
                        hostPath = AppDomain.CurrentDomain.BaseDirectory + hostPath;
                        File.Copy(hostPath, PathEtc, true);
                    }
                    catch (Exception)
                    {
                        hostPath = @"\\hioffs01\ProjectShare\OfficeLive\Temp\Hosts\" + hostName;
                        if (File.Exists(hostPath))
                        {
                            File.Copy(hostPath, PathEtc, true);
                        }
                    }
                }
            }
            catch (Exception)
            {
                hostPath = @"Source\host\hosts.clean.txt";
                hostPath = AppDomain.CurrentDomain.BaseDirectory + hostPath;
                File.Copy(hostPath, PathEtc, true);
            }
        }

        private bool SetRegedit(string proxyOverride, string proxyServer, int proxyEnable)
        {
            try
            {
                RegistryKey RegKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                RegKey.SetValue("ProxyOverride", proxyOverride);
                RegKey.SetValue("ProxyServer", proxyServer);
                RegKey.SetValue("ProxyEnable", proxyEnable);

                SetDefaultConnecSet(proxyEnable);
                RegKey.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Set if need to select "Use automation configuration script" checkBox
        /// </summary>
        /// <param name="proxyEnable"></param>
        /// <returns></returns>
        private bool SetDefaultConnecSet(int proxyEnable)
        {
            int CheckedAutoDetectID = (proxyEnable == 0) ? 09 : 03;
            try
            {
                RegistryKey RegKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections", true);
                byte[] bytesDefualtCon = (byte[])RegKey.GetValue("DefaultConnectionSettings");

                for (int i = 0; i < bytesDefualtCon.Length; i++)
                {
                    bytesDefualtCon[8] = (byte)CheckedAutoDetectID;
                    //Console.Write(" {0:X2}", bytesDefualtCon[i]);
                }

                RegKey.SetValue("DefaultConnectionSettings", bytesDefualtCon, RegistryValueKind.Binary);
                RegKey.Close();
                return true;
            }
            catch (FieldAccessException)
            {
            }
            catch (Exception)
            {
            }
            return false;
        }

        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lPBuffer, int lpdwBufferLength);
        private const int INTERNET_OPTION_REFRESH = 0x000025; private const int INTERNET_OPTION_SETTINGS_CHANGED = 0x000027;
        private static void Reflush()
        {
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
        }
    }
}
